package com.cad3d.filemanager.dbutils;

import org.apache.log4j.Logger;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateUtil {

	private static SessionFactory sessionFactory;
	private static Session session;
	static Logger logger = Logger.getLogger(HibernateUtil.class);

	public static SessionFactory getSessionFactory(){
		try {
			Configuration configuration = new Configuration();
			configuration.configure();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
			.applySettings(configuration.getProperties())
			.buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage());
		}
		return sessionFactory;
	}
	
	public static Session getSession(){
		if(session== null){
			session = HibernateUtil.getSessionFactory().openSession();
		}else{
			if(!session.isConnected()){
				//if session is closed, reopen session
				session = HibernateUtil.getSessionFactory().openSession();
			}
		}
		return session;
	}
}
